package com.iteima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iteima.reggie.common.R;
import com.iteima.reggie.entity.User;
import com.iteima.reggie.service.UserService;
import com.iteima.reggie.utils.SMSUtils;
import com.iteima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 获取验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info(user.toString());

        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){

            //获取随机4位随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("code={}",code);
            //发送短信
//            SMSUtils.sendMessage("瑞吉外卖","SMS_295791119",phone,code);
            //将正确的验证码保存到Session中,用于登录验证
            session.setAttribute(phone,code);
            return R.success("验证码已经发送,请注意查收");

        }
        return R.error("短信发送失败");
    }


    /**
     * 登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info("map={}",map.toString());
        //获取手机号码与code验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        
        //正确的验证码
        Object rightCode = session.getAttribute(phone);

        //校验
         if (rightCode != null && rightCode.equals(code)){
            //校验通过
                //判断该手|机号码是否为新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                //为新用户
                //存入数据库
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        //校验不通过
            //error
        return R.error("登录失败");
    }
}
